/*
 * 猪八戒公共函数库
 */
// window.alert=function (){};
// window.confirm=function (){};
function fixajaxdialog(){
	$('.ajaxdialog').bind('click',function (){
		title=$(this).attr('title');
		if(!title){
			title=$(this).text();
		}
		cpdialog(title,$(this).attr('href'),
			[ {
				'text' : "取消",
				'click' : 'close'
				}, {
				'text' : "确定",
				'main' : true,
				'click' : function() {
					if ($('form.dialog').size()) {
						$('form.dialog').trigger('submit');
					} else {
						cpdialogdestroy();
					}
				}
			}
			], true);
		return false;
	});
	$('.ajaxdialog-callback').bind('click',function (){
		title=$(this).attr('title');
		if(!title){
			title=$(this).text();
		}
		var args = $(this).attr('args');
		cpdialog(title,$(this).attr('href'),
			[ {
				'text' : "取消",
				'click' : 'close'
				}, {
				'text' : "确定",
				'main' : true,
				'click' : function() {
					if ($('form.dialog').size()) {
						$.ajax({
							cache: true,
							type: "POST",
							url:$('form.dialog').attr("action"),
							data:$('form.dialog').serialize(),// 你的formid
							async: false,
						    error: function(request) {
						        alert("Connection error");
						    },
						    success: function(data) {
						    	if(typeof dialogcallback == "function"){
									dialogcallback(args);
								}
							    cpdialogdestroy();
						    }
						});
					} else {
						cpdialogdestroy();
					}
				}
			}
			], true, 0);
		return false;
	});
}
function fixajaxask() {
	$('.ajaxask').bind(	'click',function() {
		var title = $(this).attr('title');
		if (!title) {
			title = $(this).text();
		}
		var url = $(this).attr('href');
		var asktext = $(this).attr('asktext') ? $(this).attr('asktext') : "您确定要" + $(this).text()+ "?";
		var linkobj=$(this);
		cpdialog(title,asktext,	[{'text':'取消','click':'close'},
			{'text':'确定','main':true,
				'click':function (){
					$.ajax({
					type : 'GET',
					url : url,
					dataType : 'json',
					beforeSend : function() {
						cploading();
					},
					complete : function() {
						cploadingdestroy();
					},
					success : function(	data,statusText) {
						if (data.msg) {
							if (data.state == 1) {
								if (data.url) {
									buttons = [ {
										'text' : '确定',
										'click' : function() {
											cpdialogdestroy();
											window.location.href = data.url;
										}
									} ];
								} else {
									buttons = [ {
										'text' : '确定',
										'click' : function() {
											cpdialogdestroy();
										}
									} ];
								}
								cpdialog("提示信息",	data.msg,buttons);
							} else if (data.state == 2) {
								buttons = [];
								if(data.linktext){
									linkobj.html(data.linktext);
								}
								cpdialog("",data.msg,buttons,false,2);
								if (data.url) {
									window.setTimeout(function() {
										window.location.href = data.url;
										}, 2000);
								}
							} else if (data.state == 3) {
								buttons = [];
								cpdialog("",data.msg,buttons,false,2);
								if(data.linktext){
									linkobj.parents(data.linktext).hide(1000,function (){$(this).remove();});
								}
								if (data.url) {
									window.setTimeout(function() {
										window.location.href = data.url;
									}, 2000);
								}
							} else {
								buttons = [ {
									'text' : '确定',
									'main' : true,
									'click' : 'close'
								} ];
								cpdialog("提示信息",data.msg,buttons);
							}
						}
					}
					});
				}
			}
			], false);
			return false;
		});
}
function fixajax() {
	$('.ajax').bind('click',function() {
		var title = $(this).attr('title');
		if (!title) {
			title = $(this).text();
		}
		var url = $(this).attr('href');
		var linkobj=$(this);
		$.ajax({
			type : 'GET',
			url : url,
			dataType : 'json',
			beforeSend : function() {
				cploading();
			},
			complete : function() {
				cploadingdestroy();
			},
			success : function(	data,statusText) {
				if (data.msg) {
					if (data.state == 1) {
						if (data.url) {
							buttons = [ {
								'text' : '确定',
								'click' : function() {
									cpdialogdestroy();
									window.location.href = data.url;
								}
							} ];
						} else {
							buttons = [ {
								'text' : '确定',
								'click' : function() {
									cpdialogdestroy();
								}
							} ];
						}
						cpdialog("提示信息",	data.msg,buttons);
					} else if (data.state == 2) {
						buttons = [];
						if(data.linktext){
							linkobj.html(data.linktext);
						}
						cpdialog("",data.msg,buttons,false,2);
						if (data.url) {
							window.setTimeout(function() {
								window.location.href = data.url;
								}, 2000);
						}
					} else if (data.state == 3) {
						buttons = [];
						cpdialog("",data.msg,buttons,false,2);
						if(data.linktext){
							linkobj.parents(data.linktext).hide(1000,function (){$(this).remove();});
						}
						if (data.url) {
							window.setTimeout(function() {
								window.location.href = data.url;
							}, 2000);
						}
					} else {
						buttons = [ {
							'text' : '确定',
							'main' : true,
							'click' : 'close'
						} ];
						cpdialog("提示信息",data.msg,buttons);
					}
				}
			}
		});
		return false;
	});
}
function fixdatepicker(options){
	$('.datetimepicker').attr('data-format','yyyy-MM-dd hh:mm:ss').wrap('<span></span>');
	$('.datepicker').attr('data-format','yyyy-MM-dd').wrap('<span></span>');
	if(options){
		options.language='zh-CN';
		options.pickTime=true;
		$('.datetimepicker').parent().datetimepicker(options);
		options.pickTime=false;
		$('.datepicker').parent().datetimepicker(options);
	}else{
		$('.datepicker').parent().datetimepicker({
		      pickTime: false,
			  today:true,
		      language: 'zh-CN'
	    });
		$('.datetimepicker').parent().datetimepicker({
		      pickTime: true,
			  today:true,
		      language: 'zh-CN'
	    });
	}
}
$(document).ready(function() {
	cpdialogdestroy();
	cploadingdestroy();
	fixajaxask();
	fixajaxdialog();
	fixdatepicker();
	fixajax();
});
function htmlload(htmlobj, url, func, postdata) {
	cploading();
	if ($.isFunction(func)) {
		$(htmlobj).load(url, postdata, function() {
			cploadingdestroy();
			func();
		});
	} else {
		$(htmlobj).load(url, postdata, function() {
			cploadingdestroy();
		});
	}
}
function cpdialog(title, html, buttons, isurl, autodestorytime) {
	cploadingdestroy();
	cpdialogdestroy();
	$("#dialog").draggable();
	$("#dialog .modal-header h3").html(title);
	if (isurl) {
		htmlload($("#dialog .modal-body"), html);
	} else {
		$("#dialog .modal-body").html(html);
	}
	$("#dialog .modal-footer a").each(function(index, item) {
		$(this).unbind('click').remove();
	});
	if (buttons) {
		$.each(buttons,function(index, item) {
			if (item.click == 'close') {
				if (item.main) {
					$("#dialog .modal-footer").html($("#dialog .modal-footer").html()+ '<a href="#" class="btn btn-success" data-dismiss="modal">'+ item.text+ '</a>');
				}else{
					$("#dialog .modal-footer").html($("#dialog .modal-footer").html()+ '<a href="#" class="btn" data-dismiss="modal">'+ item.text+ '</a>');
				}
			} else {
				if ($.isFunction(item.click)) {
					if (item.main) {
						$("#dialog .modal-footer").html($("#dialog .modal-footer").html()+ '<a href="javascript:" class="btn btn-success">'+ item.text+ '</a>');
					} else {
						$("#dialog .modal-footer").html($("#dialog .modal-footer").html()+ '<a href="javascript:" class="btn">'+ item.text+ '</a>');
					}
				} else {
					$("#dialog .modal-footer").html($("#dialog .modal-footer").html()+ '<a href="javascript:" class="btn btn-warning">'+ item.text+ '</a>');
				}
			}
		});
		$.each(buttons, function(index, item) {
			if (item.click == 'close') {
			} else {
				if ($.isFunction(item.click)) {
					$("#dialog .modal-footer").find('a').eq(index).bind(
							'click', item.click);
				} else {
					$("#dialog .modal-footer").find('a').eq(index).bind('click', function() {
						alert('绑定的函数不合法')
					});
				}
			}
		});
	}
	if(autodestorytime){
		window.setTimeout(function (){
			cpdialogdestroy();
		},autodestorytime*1000);
	}
	$("#dialog").modal({'show' : true});
}
function cploading() {
	$("#cploading").modal({	'show' : true});
}
function cploadingdestroy() {
	$("#cploading").modal('hide');
}
function cpdialogdestroy() {
	$("#dialog").modal('hide');
}
function ajaxform(jqueryfrom, beforeSubmit,afterSucess) {
	jqueryfrom.submit(function() {
		jqueryfrom = $(this);
		$(this).ajaxSubmit({
			dataType : 'json',
			beforeSend : function(data) {
				jqueryfrom.find('.control-group').each(
					function(index,item) {
						if ($(this).hasClass('error')&& $(this).find('span.help-inline,span.help-block').data('orgtext')) {
							$(this).removeClass('error').find('span.help-inline,span.help-block').html($(this).find('span.help-inline,span.help-block').data('orgtext'));
						} else if($(this).hasClass('error')) {
							$(this).removeClass('error').find('span.help-inline,span.help-block').remove();
						}
					});
				jqueryfrom.find('.alert-block').remove();
				cploading();
			},
			beforeSubmit : function(arr, form,options) {
				if ($.isFunction(beforeSubmit)) {
					return beforeSubmit(arr, form,options);
				}
				return true;
			},
			success : function(data, statusText) {
				cploadingdestroy();
				if (data.msg) {
					if (data.state == 1) {
						if (data.url) {
							buttons = [ {
								'text' : '确定',
								'click' : function() {
									cpdialogdestroy();
									window.location.href = data.url;
								}
							} ];
						} else {
							buttons = [ {
								'text' : '确定',
								'click' : function() {
									cpdialogdestroy();
								}
							} ];
						}
						cpdialog("提示信息",data.msg,buttons);
					} else if (data.state == 2) {
						buttons = [];
						cpdialog("",data.msg,buttons,false,2);
						if (data.url) {
							window.setTimeout(function() {
								window.location.href = data.url;
								}, 2000);
						}
					} else {
						if (data.field) {
							if (jqueryfrom.find('input[name='+ data.field+ ']').parents('.control-group').size()
									|| jqueryfrom.find('textarea[name='+ data.field+ ']').parents('.control-group').size()
									|| jqueryfrom.find('select[name='+ data.field+ ']').parents('.control-group').size()) {
								obj = jqueryfrom.find('input[name='+ data.field+ '],textarea[name='+ data.field+ '],select[name='+ data.field+ ']').parents('.control-group');
								obj.addClass('error');
								if (obj.find('.help-inline,.help-block').size()) {
									html = obj.find('.help-inline,.help-block').html();
									obj.find('.help-inline,.help-block').data('orgtext',html).html(data.msg);
								} else {
									obj.find('.controls').append('<span class=\"help-inline\">'+ data.msg+ '</span>');
								}
							} else {
								jqueryfrom.prepend('<div class=\"alert alert-block alert-error\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>'+ data.msg+ '</div>');
							}
						}else{
							jqueryfrom.prepend('<div class=\"alert alert-block alert-error\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>'+ data.msg+ '</div>');
						}
						if (data.url) {
							window.setTimeout(function() {
								window.location.href = data.url;
								}, 2000);
						}
					}
				}
				if ($.isFunction(afterSucess)) {
					return afterSucess(data, statusText);
				}
			}
		});
		return false;
	});
}
function geturlparam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
function replaceurlparam(name,value, pathname) {
	if(pathname == undefined) {
		 var reg = new RegExp("(^|&)" + name + "=[^&]*", "i");
	    if(geturlparam(name)){
	    	window.location.search='?'+window.location.search.substr(1).replace(reg,RegExp.$1+name+'='+value);
	    }else{
	    	if(window.location.search.match(/^\?/)){
	    		window.location.search=window.location.search+'&'+name+'='+escape(value);
	    	}else{
	    		window.location.search='?'+name+'='+escape(value);
	    	}
	    }
	}else{
		 var reg = new RegExp("(^|&)" + name + "=[^&]*", "i");
		 
	    if(geturlparam(name)){
	    	window.location.href = pathname + '?'+window.location.search.substr(1).replace(reg,RegExp.$1+name+'='+value);
	    }else{
	    	if(window.location.search.match(/^\?/)){
	    		window.location.href = pathname +window.location.search+'&'+name+'='+escape(value);
	    	}else{
	    		window.location.href = pathname + '?'+name+'='+escape(value);
	    	}
	    }
	}
   
}
/*
 * function: create and show date picker
 * @param trigger DOM id
 */
$(document).ready(function () {
    $('.parent-menu-item').bind({
      click: function() {
        $('.parent-menu-item').children('ul').hide();
        $(this).children('ul').show();
      },
      mouseout: function() {
        //$(this).children('ul').hide();
      }
    });
    $('#live-msg-container').hide(); 
    
    $('#click_close_x_a').click(function(){
    	$('#live-msg-container').hide(); 
    });
    $("#icon-envelope-href").click(function(){
//    	alert($("#"))
    	$("#msgRemindUl").toggle();
    });
    /**
     * 获取提醒
     */
    //V5注释，不要提交到线上
    getRemind();
    setInterval(getRemind, "30000");//测试使用，30秒刷新数据
	function getRemind(){
		/**
		 * 获取邮件个数
		 */
		$.getJSON("/cpuser/OAEmailNum", function(data){
			if(data.data.num > 0) {
				$('#zhubajietpl_mail_num').text(data.data.num);
			}
		});
		/**
		 * 获取工作流个数
		 */
		$.getJSON("/cpuser/OAWorkFlowNum", function(data){
			if(data.num > 0) {
				$('#zhubajietpl_workflow_num').text(data.num);
			}
		});
		/**
		 * 获取消息提醒
		 */
		$.getJSON("/cpuser/msgRemind", function(data){
			var msgStr = '';
			var title = '';
			var cont = '';
			if(data != null) {
				$.each(data.msg, function(i, item){
					if(item.title.substr(0,42) != item.title){
						title = item.title.substr(0,42)+'...';
					}else{
						title = item.title;
					}
					if(item.cont.substr(0,28) != item.cont){
						cont = item.cont.substr(0,28)+'...';
					}else{
						cont = item.cont;
					}
					msgStr += '<li><small><strong>'+title+'</strong></small></li><li><small><a href="/cpuser/msglist-num-'+data.num+'" target="_blank">'+cont+'</a></small></li><li class="divider"></li>';
				});
				msgStr += '<li><small>共'+data.num+'条新消息</small><small class="pull-right"><a id="msgRemindAll" href="/cpuser/msglist-num-'+data.num+'" target="_blank">全部>>&nbsp;&nbsp;</a></small></li>';
				if(data.num > 0 ) {
					$("#unreadMsgNum").text(data.num);
					$("#msgRemindUl").show();
				}else{
					$("#msgRemindUl").hide();
				}
			}else{
				$("#msgRemindUl").hide();
				msgStr += '<li><small>共0条新消息</small><small class="pull-right"><a href="/cpuser/msglist-num-0" target="_blank">全部>>&nbsp;&nbsp;</a></small></li>';
			}
			
			$("#msgRemindUl").html(msgStr);
		})
		/**
		 * 获取提醒
		 */
		$.getJSON("/cpuser/remindalllist", function(data){
			var shiwuMsgStr = '';
			var orderMsgStr = '';
    		$.each(data.data, function(i, item){
    			if(item.type == '超期工单' || item.type == '今日到期工单' || item.type == '待处理工单') {
    				if(item.value > 0) {
    					orderMsgStr += '<li><span><a href="../'+item.url+'">'+item.type+'&nbsp;</a></span><span style="color: red">'+item.value+'</span></li>';
    				}else{
    					orderMsgStr += '<li><span><a href="../'+item.url+'">'+item.type+'</a></span></li>';
    				}
				}else{
					if(item.value > 0) {
						shiwuMsgStr += '<li><span><a href="../'+item.url+'">'+item.type+'&nbsp;</a></span><span style="color: red">'+item.value+'</span></li>';
					}else{
						shiwuMsgStr += '<li><span><a href="../'+item.url+'">'+item.type+'</a></span></li>';
					}
				}
    		})
    		//orderMsgStr += '<li><span><a href="../index">+创建工单</a></span></li>';
    		$('#my_shiwu_ul').html(shiwuMsgStr);
    		$('#my_order_ul').html(orderMsgStr);
    	});
	}
  });
//marquee('marquee');
//获取话题，跑马灯
$.getJSON("/misc/topicTopList",function(data){
	var topicStr = "";
	$.each(data, function(i, item){
		topicStr += '<li><a href="../misc/topicdetail-id-'+item.topic_id+'" target="_blank">'+item.title;
		if(item.giftnum > 0) {
			topicStr += '<i class="icon-gift"></i><span style="color: red">共收到'+item.giftnum+'个礼物</span>';
		}
		topicStr += '</a></li>';
	});
	$("#topicTopListUl").html(topicStr);
	marquee('marquee');
});
function marquee(id) {
	  var container = document.getElementById(id),
	    original = container.getElementsByTagName("ul")[0],
	    clone = container.getElementsByTagName("ul")[1],
	    timer = null,
	    speed = arguments[1] || 10
	  	clone.innerHTML = original.innerHTML;
	  var roll = function () {
	    if(container.scrollLeft === clone.offsetLeft) {
	      container.scrollLeft = 0;
	    } else {
	      container.scrollLeft++;
	    }
		
	  }
	  timer = setInterval(roll, speed);

	  container.onmouseover = function () {
	    clearInterval(timer)
	  }
	  container.onmouseout = function () {
	    timer = setInterval(roll, speed)
	  }
	}

/*------------------search------------------------*/
$("#searchBoxInMenuBar").keyup(function(){
	var val=$("#searchBoxInMenuBar").val();
	if(val.length>0){
		$("#search_menu").show();
		//if(val.length>20){
		//	val=val.substr(0,20);
		//}
		//$("#search_menu .words").text('"' + val + '"' );
		$(".advsearch .adv_out").hide();
	}else{
		$("#search_menu").hide();
	}
});
document.onclick=function(){
	$("#search_menu").hide();
}
$("#searchBoxInMenuBar").focus(function(){
	//$("#search_menu").show();
});
$(".search_item a").click(function(){
	$(this).attr("href","/misc/search?type="+$(this).attr("typeid")+"&key="+encodeURIComponent($("#searchBoxInMenuBar").val()) );
});
$("#navbar-search-form").submit(function(){
	var val=encodeURIComponent($("#searchBoxInMenuBar").val());
	if(val.length<1){
		 cpdialog("搜索","请输入关键字",[{"text":"确定","click":"close"}]);
		return false;
	}
	//$("#navbar-search-form").attr("action",$("#navbar-search-form").attr("action")+ val);
});
$(".advsearch .adv").click(function(){
	$("#search_menu").hide();
	$(".advsearch .adv_out").slideToggle();
	$(".advsearch .adv_key").val($("#searchBoxInMenuBar").val());
});
option=['<option value="0">怎么搜</option>','<option value="1">标题</option><option value="2">交易号</option><option value="3">投标号</option><option value="4">买家昵称</option>','<option value="1">标题</option><option value="2">服务号</option><option value="3">昵称</option>','<option value="1">昵称</option><option value="2">ID</option><option value="3">用户名</option><option value="4">认证手机</option><option value="5">联系电话</option><option value="6">认证邮箱</option><option value="7">联系邮箱</option><option value="8">易极付ID</option><option value="9">证件号</option>','<option value="1">举报编号</option>','<option value="1">标签名称</option>','<option value="1">工单ID</option>'];
$(".advsearch .type").change(function(){
	$(".advsearch .subtype").html(option[$(this).val()]);
}).change();
/*------------------lightbox------------------------*/
if($("a.lightbox").size()>0){
	$("head").append('<script type="text/javascript" src="/assets/fancybox/fancybox.js"></script><link rel="stylesheet" type="text/css" href="/assets/fancybox/fancybox.css" media="screen" />');
	$(".lightbox").fancybox({
        padding: 0,
        openEffect : 'elastic',
        openSpeed  : 150,
        closeEffect : 'elastic',
        closeSpeed  : 150,
        closeClick : true,
        helpers : {
          overlay : null
        }
    });
}

//json2
if(typeof JSON!=="object"){JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}());

;(function(){
    /** 设置COOKIE */
    function SetCookie (name, value) {
        var argv = SetCookie.arguments;
        var argc = SetCookie.arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + value
            + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
            + ((path == null) ? "" : ("; path=" + path))
            + ((domain == null) ? "" : ("; domain=" + domain))
            + ((secure == true) ? "; secure" : "");
    }
    /** 获取COOKIE */
    function GetCookie (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg){
                return getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    }
    /** 删除COOKIE */
    function DeleteCookie (name) {
        var exp = new Date();
        exp.setTime (exp.getTime() - 1);
        var cval = 0;
        document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    }
    function getCookieVal(offset) {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1)endstr = document.cookie.length;
        return document.cookie.substring(offset, endstr);
    }
    window.ZDK = window.ZDK || {};
    ZDK.cookie = {
        setCookie: SetCookie,
        getCookie: GetCookie,
        deleteCookie: DeleteCookie
    }
})();
/* 推荐威客 */
(function(){
    var inviteWitkey = {
        data: {
            taskId: 0,
            witkeyList: []
        },
        init: function(){
            var self = this;
            this.loadData();
            var inviteBtn = $('a.invitetask-user');
            if ( !inviteBtn.size() ) {
                return;
            }
            if ( this.data.witkeyList.length || this.data.taskId ) {
                this.buildTip();
            }
            inviteBtn.on('click', function(){
                self.addWitkey( $(this).attr('data-username'), $(this).attr('data-uid'), $(this) );
            });
            $(document.body).delegate('div.witkey-recmd-box li a', 'click', function(){
                self.deleteWitkey( $(this).attr('data-uid') );
            });
            $(document.body).delegate('#j-dorecmd', 'click', function( evt ){
                evt.preventDefault();
                self.sendRecmdWitkey();
            });
            $(document.body).delegate('#j-dodiscard', 'click', function( evt ){
                evt.preventDefault();
                self.destroy();
            });

            $(document.body).delegate('#j-recmd-taskId', 'blur', function( evt ){
                self.updateTaskId();
            });
        },
        sendRecmdWitkey: function(){
            var self = this;
            var data = $('#j-recmdwitkey-form').serialize();
            $.post('/user/SendSingle', data, function( evt ){
                if ( evt.state  == 1  ) {
                    alert('推荐威客成功');
                    self.data.taskId = '';
                    self.data.witkeyList = [];
                    self.saveData();
                } else {
                    alert(evt.msg);
                }
            },'json');
        },
        destroy: function(){
            $('div.witkey-recmd-box').remove();
            this.data.taskId = '';
            this.data.witkeyList = [];
            ZDK.cookie.deleteCookie('taskId');
            ZDK.cookie.deleteCookie('witkeyList');
        },
        deleteWitkey: function( uid ){
            var witkeyList = this.data.witkeyList;
            for( var i = 0; i < witkeyList.length; i++){
                if( witkeyList[i].uid == uid ){
                    witkeyList.splice(i, 1);
                }
            }
            this.saveData();
        },
        updateTaskId: function(){
            this.data.taskId = $('#j-recmd-taskId').val();
            this.saveData( 1 );
        },
        addWitkey: function( username, uid, obj ){
            $(obj).html('推荐中.....');
            var self = this;
            $.get('/user/isSingeOk?uid=' + uid, {}, function( evt ){
                if ( evt.state  == 1  ) {
                    doAdd();
                } else {
                    alert(evt.msg);
                    $(obj).html('推荐Ta');
                }
            },'json');

            function doAdd(){
                var witkeyList = self.data.witkeyList;
                if( witkeyList.length == 3 ){
                    alert('只能推荐三个');
                    $(obj).html('推荐Ta');
                    return;
                }
                for( var i = 0; i < witkeyList.length; i++){
                    if( witkeyList[i].uid == uid ){
                        alert( username + '已经被推荐' );
                        $(obj).html('推荐Ta');
                        return;
                    }
                }
                $(obj).html('已推荐');
                witkeyList.push({uid: uid, username: username});
                self.saveData();
            }
        },
        buildTip: function(){
            if ( $('div.witkey-recmd-box') ) {
                $('div.witkey-recmd-box').remove();
            }
            var taskId = this.data.taskId||'';
            var witkeyList = this.data.witkeyList;
            var html = [];
            html.push('<div class="witkey-recmd-box" id="j-witkey-recmd-box"><form id="j-recmdwitkey-form"><div  class="witkey-recmd-hd"><h3>推荐威客</h3></div>');
            html.push('<div class="witkey-recmd-bd">');
            html.push('<div><label>订单号</label><input type="text" name="taskId" value="'+ taskId +'" id="j-recmd-taskId"/></div><div>已选择的威客(最多三个)</div>');
            html.push('<ul id="j-witkey-recmdlist">');
            for( var i = 0; i < witkeyList.length;i++ ){
                html.push( this.tpl(witkeyList[i]) );
            }
            html.push('</ul>');
            html.push('</div><div class="witkey-recmd-ft"><a class="btn"  id="j-dodiscard">取消</a><a class="btn btn-primary" id="j-dorecmd">确定</a></div></form><div>');
            $(html.join('')).appendTo(document.body);
            $("#j-witkey-recmd-box").draggable();
        },
        saveData: function( silent ){
            ZDK.cookie.setCookie('taskId', this.data.taskId);
            ZDK.cookie.setCookie('witkeyList', JSON.stringify(this.data.witkeyList));
            if ( silent ) {
                return;
            }
            this.buildTip();
        },
        loadData: function(){
            var taskId;
            if ( $('#single_task_id').size() ) {
                taskId = $('#single_task_id').val();
                ZDK.cookie.setCookie('taskId', taskId);
            } else {
                taskId = ZDK.cookie.getCookie('taskId');
            }

            var witkeyList = ZDK.cookie.getCookie('witkeyList');
            witkeyList = JSON.parse(witkeyList);
            this.data.taskId = taskId||'';
            this.data.witkeyList = witkeyList||[];
        },
        tpl: function( data ){
            return '<li>'+ data.username +'<a data-uid="'+ data.uid +'" href="javascript:void(0)">x</a><input type="hidden" name="witkeyId[]" value="'+ data.uid +'"/> </li>';
        }
    };

    inviteWitkey.init();

})();
// BUG: 1.官方派单的后台，已推荐的状态没有及时更新，当我取消了威客的时候，状态还是“已推荐”
// boss后台的测试地址是
// http://boss.t6.zbj.com/cp-index
// 可以使用测试帐号登录：
// 帐号：刘学成
// 密码：Bajie295